package com.etonedu.meals;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.MotionEvent;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.etonedu.meals.base.BaseApplication;
import com.etonedu.meals.base.SystemBaseFragment;
import com.etonedu.meals.bean.AttenRuleBean;
import com.etonedu.meals.bean.DeviceDetaiBean;
import com.etonedu.meals.bean.DeviceInfoBean;
import com.etonedu.meals.bean.Result;
import com.etonedu.meals.bean.ResultToken;
import com.etonedu.meals.bean.TimeList;
import com.etonedu.meals.common.SPConst;
import com.etonedu.meals.dao.DaoUtils;
import com.etonedu.meals.enumeration.APICodeEnum;
import com.etonedu.meals.http.HttpUrl;
import com.etonedu.meals.http.IGetUrl;
import com.etonedu.meals.http.LogReportUtils;
import com.etonedu.meals.http.ParamsUtils;
import com.etonedu.meals.http.Request;
import com.etonedu.meals.http.xutils.NewXUtilsRequest;
import com.etonedu.meals.http.xutils.NewXUtilsResponse;
import com.etonedu.meals.receiver.TimeChangeReceiver;
import com.etonedu.meals.runtimepermissions.PermissionsManager;
import com.etonedu.meals.runtimepermissions.PermissionsResultAction;
import com.etonedu.meals.service.CardLogService;
import com.etonedu.meals.service.CardService;
import com.etonedu.meals.service.DeamService;
import com.etonedu.meals.service.MachineService;
import com.etonedu.meals.service.OffOpenService;
import com.etonedu.meals.service.UploadService;
import com.etonedu.meals.utils.SharedPreferencesUtil;
import com.etonedu.meals.utils.Utils;
import com.etonedu.meals.utils.WindowUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.http.HttpMethod;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import io.objectbox.Box;

public class MainActivity extends AppCompatActivity {

    private SharedPreferencesUtil spu;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_main);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        mScreenHeight = displayMetrics.heightPixels;

        spu = SharedPreferencesUtil.getInstance(x.app());

        init();
        registerXgPush();
    }

    private int downY;
    protected int mScreenHeight = 0;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downY = (int) ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                int thisY = (int) ev.getY();
                int result = thisY - downY;
                if (result >= mScreenHeight / 2) {
                    WindowUtils.showManageDialog(MainActivity.this);
                }
                break;
        }

        try {
            return super.dispatchTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = new Intent(this, DeamService.class);
        startService(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (timeChangeReceiver != null) {
            unregisterReceiver(timeChangeReceiver);
        }
    }

    @Subscribe
    public void onEvent(String msg) {
        if ("切换环境".equals(msg)) {
            init();
        }
    }

    TimeChangeReceiver timeChangeReceiver;

    //获取当前日期
    private void initTick() {

        if (timeChangeReceiver != null) {
            unregisterReceiver(timeChangeReceiver);
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);//每分钟变化
        timeChangeReceiver = new TimeChangeReceiver();
        registerReceiver(timeChangeReceiver, intentFilter);
    }

    private void init() {
        if (HttpUrl.DOMAIN.equals("http://agw.52ess.cn/api")) {
            spu.setString(SPConst.ENVIRONMENT, "TEST01");
        } else if (HttpUrl.DOMAIN.equals("http://agw.woniukid.cn/api")) {
            spu.setString(SPConst.ENVIRONMENT, "PROD01");
        } else if (HttpUrl.DOMAIN.equals("http://47.106.165.234:8181/api")) {
            spu.setString(SPConst.ENVIRONMENT,"TEST02");
        } else if (HttpUrl.DOMAIN.equals("http://123.207.103.39:8080/api")) {
            spu.setString(SPConst.ENVIRONMENT, "PROD02");
        }

        String hostUrl = spu.getString(SPConst.HOST_URL);
        LogUtils.e("hostUrl = " + hostUrl);
        LogUtils.e("url = " + HttpUrl.DOMAIN);

        if (!Utils.isEmpty(hostUrl)) {

            HttpUrl.setDomain(hostUrl);
        }

        String appDir = Utils.getSDPath() + "/yjtApp";
        FileUtils.delete(appDir);

        getPublicUrl();

        initTick();

        initPermissions();

        initCardService();
        initUploadService();
    }

    public void getPublicUrl() {
        String apiCode = APICodeEnum.agw10111006.getApiCode();

        String type = spu.getString(SPConst.ENVIRONMENT);

        String url = spu.getString(SPConst.AGW_10111006);

        if (!Utils.isEmpty(url)) {
            getToken4Url(apiCode,url);
            return;
        }

        Request request = new Request();
        request.getPublicUrl(apiCode, type);
        request.setGetUrl(new IGetUrl() {
            @Override
            public void success(String content) {
                LogUtils.e("content = " + content);
                spu.setString(SPConst.AGW_10111006, content);
                getToken4Url(apiCode,content);
            }

            @Override
            public void fail(String content) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPublicUrl();
                    }
                },3*1000);
            }
        });
    }

    private void getToken4Url(String apiCode, String url) {
        String header = ParamsUtils.getHeader(apiCode, "");

        String params = ParamsUtils.getTokenParams();

        String data = ParamsUtils.getEncrypt(apiCode, params);

        String data1 = ParamsUtils.getParams(apiCode, data);

        NewXUtilsRequest request = new NewXUtilsRequest(header, data1);

        request.requet(url, apiCode, HttpMethod.POST, new NewXUtilsResponse() {
            @Override
            public void response(String type, String result) {
                try {
                    Type typeToken = new TypeToken<Result>() {
                    }.getType();
                    Gson gson = new Gson();
                    Result r = gson.fromJson(result, typeToken);

                    String rescode = r.getRescode();

                    String data = r.getData();

                    String deData = ParamsUtils.getDecrypt(apiCode,data);

                    LogUtils.json(deData);
                    if (!TextUtils.isEmpty(deData)) {
                        Type token = new TypeToken<ResultToken>() {
                        }.getType();
                        ResultToken resultToken = gson.fromJson(deData, token);

                        SharedPreferencesUtil spu = SharedPreferencesUtil.getInstance(x.app());
                        spu.setString(SPConst.TOKEN, resultToken.getToken());

                        String tokenStr = resultToken.getToken();

                        initMachineService();

                        devcode4BingdUrl(tokenStr);
                        LogReportUtils.getPublicUrl(tokenStr);
                        LogReportUtils.getPublicStateUrl("1");
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                LogReportUtils.stateReportPublicUrl();
                            }
                        }, 1 * 1000);
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void error(String type, String msg) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPublicUrl();
                    }
                },3*1000);
            }
        });
    }

    private void devcode4BingdUrl(String token) {
        String apiCode = APICodeEnum.agw30161009.getApiCode();
        String type = spu.getString(SPConst.ENVIRONMENT);

        String url = spu.getString(SPConst.AGW_30161009);
        if (!Utils.isEmpty(url)) {
            devcode4Bingd(url, token);
            return;
        }

        Request request = new Request();
        request.getPublicUrl(apiCode, type);
        request.setGetUrl(new IGetUrl() {
            @Override
            public void success(String content) {
                LogUtils.e("content = " + content);
                spu.setString(SPConst.AGW_30161009, content);
                devcode4Bingd(content, token);
            }

            @Override
            public void fail(String content) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPublicUrl();
                    }
                },3*1000);
            }
        });
    }

    private void devcode4Bingd(String url,String token) {
        String model = Build.MODEL;
        String apiCode = APICodeEnum.agw30161009.getApiCode();

        String header = ParamsUtils.getHeader(apiCode, token);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deviceCode", Utils.getDevCode());
        hashMap.put("modelNo", model);
        hashMap.put("appVersion", Utils.getVersionCode(this));
        hashMap.put("currentTime", new Date().getTime());
        hashMap.put("dayNum", 7);
        Gson gson = new Gson();
        String json = gson.toJson(hashMap);

        String data = ParamsUtils.getEncrypt(apiCode, json);

        String data1 = ParamsUtils.getParams(apiCode, data);

        NewXUtilsRequest request = new NewXUtilsRequest(header, data1);

        request.requet(url, apiCode, HttpMethod.POST, new NewXUtilsResponse() {
            @Override
            public void response(String type, String result) {
                Type typeToken = new TypeToken<Result>() {
                }.getType();
                Gson gson = new Gson();
                Result r = gson.fromJson(result, typeToken);

                String data = r.getData();


                if (!Utils.isEmpty(data)) {
                    String deData = ParamsUtils.getDecrypt(apiCode, data);
                    LogUtils.json(deData);

                    Type devType = new TypeToken<DeviceInfoBean>() {
                    }.getType();
                    DeviceInfoBean devBean = gson.fromJson(deData, devType);

                    if (devBean != null) {
                        int ifBind = devBean.getIfBind();
                        String qrcContent = devBean.getQrcContent();

                        DeviceDetaiBean db = devBean.getAgwEcbDeviceDetailDto();

                        if (db != null) {
                            spu.setString(SPConst.ATTEN_MODE,db.getAttenMode());
                            spu.setString(SPConst.TEMPLATE_CODE, db.getTemplateCode());
                            spu.setString(SPConst.CLASS_NAME, db.getDeptName());
                            spu.setString(SPConst.ROOM_NAME,db.getRoomName());
                            spu.setString(SPConst.SCHOOL_NAME, db.getSchoolName());
                            spu.setInt(SPConst.IS_ACCURATE,db.getIsAccurate());

                        }

                        if (ifBind == 1) {// 已经绑定班级
                            AttenRuleBean arb = db.getAttenRuleDto();
                            if (arb != null) {
                                List<TimeList> list = arb.getTimeList();
                                if (!Utils.listIsNullOrEmpty(list)) {

                                } else {
                                    Box<TimeList> box = DaoUtils.getBoxTimeList();
                                    box.removeAll();
                                }

                            }
                            updateInterface();
                        } else {
                            spu.setString(SPConst.TEMPLATE_CODE, "QR1001");
                            spu.setString(SPConst.ADD_QR, qrcContent);
                            updateInterface();
                        }
                    }
                }
            }

            @Override
            public void error(String type, String msg) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPublicUrl();
                    }
                },3*1000);
            }
        });
    }

    private void initPermissions() {
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                LogUtils.e("申请权限成功");

            }

            @Override
            public void onDenied(String permission) {
                LogUtils.e("申请权限失败");
            }
        });
    }

    private Intent cardIntent,onoffIntent;
    private void initCardService() {
        String model = Build.MODEL;
        cardIntent = new Intent(this, CardService.class);
        startService(cardIntent);

        if ("ZC-83E".equals(model)) {
            onoffIntent = new Intent(this, OffOpenService.class);
            startService(onoffIntent);
        }
    }

    private void initMachineService() {
        Intent intent = new Intent(MainActivity.this, MachineService.class);
        startService(intent);

    }

    private void initUploadService() {
        Intent intent = new Intent(this, UploadService.class);
        startService(intent);

        Intent intent1 = new Intent(this, CardLogService.class);
        startService(intent1);

    }

    private void insertTimeList(List<TimeList> timeList) {
        try {
            Box<TimeList> box = DaoUtils.getBoxTimeList();
            box.put(timeList);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e(e.getMessage());
        }
    }

    private SystemBaseFragment systemBaseFragment;

    public void updateInterface() {


        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();

        if (systemBaseFragment != null) {
            transaction.remove(systemBaseFragment);
        }

        systemBaseFragment = new SystemBaseFragment();

        Bundle bundle = new Bundle();
//        bundle.putInt("interfaceType", interfaceType);
//        bundle.putString("classId", classId);
//        bundle.putString("deviceCode", deviceCode);
//        bundle.putSerializable("ext", templateDiy);
        systemBaseFragment.setArguments(bundle);
        transaction.replace(R.id.fl_container, systemBaseFragment);
        transaction.commitAllowingStateLoss();
    }

    // 注册信鸽
    private void registerXgPush() {
        String devId = Utils.getDevCode();
        LogUtils.e("devId = " + devId);

    }
}
